package cn.my.framework.config.shiro;

import cn.my.framework.util.CommonUtils;
import cn.my.framework.util.ConstantData;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.credential.SimpleCredentialsMatcher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by zhangl_lc on 2017/8/1.
 */
public class MyCredentialsMatcher extends SimpleCredentialsMatcher {

    Logger logger = LoggerFactory.getLogger(MyCredentialsMatcher.class);

    @Override
    public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) {
        UsernamePasswordToken loginToken = (UsernamePasswordToken)token;
        String username = loginToken.getUsername();
        if(ConstantData.loginLimitTimes > 0){
            int times = CommonUtils.incrementAndGetLoginTimes(username);
            if(times > ConstantData.loginLimitTimes){
                throw new ExcessiveAttemptsException();
            }
        }
        String loginCredential = new String(loginToken.getPassword());                    //登录传入的密码信息
        String storedCredential = (String)info.getCredentials();                          //Realm提取的用户密码信息,即存储到数据库的密码信息
        //TODO 密码的包装操作，略...

        boolean matches = StringUtils.equals(loginCredential,storedCredential);
        if(matches && ConstantData.loginLimitTimes > 0){
            CommonUtils.clearLoginTimes(username);
        }
        return matches;
    }
}
